<?php
namespace Wap\Controller;
use Common\Model\UserModel;
use Common\Model\WeixinModel;
use Wap\BaseController;
use Common\Model\EventsModel;
use Common\Model\PointMallModel;
use Common\Model\UtilsModel;
class EventsController extends BaseController {
    //活动首页
    public function index(){
        $uid=session('uid')+0;



        UserModel::addUserValByAction($uid,OPT_ENTER_EVENT);
        session('tip',S('tip_'.$uid));
        $this->smarty->assign('userinfo',session());
        
        
        $channel = I('get.channel',0,'intval');
        $fid = I('get.fid',0,'intval');

        $data = EventsModel::getEventsList($uid,1,8,$channel,CLIENT_SHOW_WAP,'',$fid);
        $channel = getChannelKv(OBJ_TYPE_ACTIVITY);
        $this->smarty->assign('eventsChannel',$channel);
        $this->smarty->assign('title',C('SITE_NAME').'-活动列表');
        $this->smarty->assign('data',$data['data']);

        if($this->isWechat) {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            //微信分享相关
            $this->smarty->assign('isWxShare', true);
            $this->smarty->assign('wxTitle', "丸子妈妈-亲子活动");
            $this->smarty->assign('wxDesc',"每周可免费参加儿童剧、电影、郊游、教育、职业体验等各种亲子活动！");
            $this->smarty->assign('wxLink', $protocol.$_SERVER['HTTP_HOST'].U("index"));
            $this->smarty->assign('wxImage', "http://wzma.176dp.cn/Public/Wap/images/logo.jpg");
            $this->smarty->assign('wxObjType',OBJ_TYPE_ACTIVITY);
            $this->smarty->assign('wxObjID',0);
        }

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->display("Event_v2/index.html");
    }

    //加载更多
    public function loadMore(){
        $page = I('get.page',2,'intval');
        $channel = I('get.channel',0,'intval');
        $my = I('get.my',0,'intval');
        $uid=session('uid')+0;
        if($my) $data = EventsModel::getMyEventsList($uid,$page,8);
        else $data = EventsModel::getEventsList($uid,$page,8,$channel,CLIENT_SHOW_WAP);


        $this->smarty->assign('data',$data['data']);
        $html = $this->smarty->fetch('Event_v2/more.html');
        $this->ajaxReturn(array('status'=>0, 'dataHTML'=>$html, 'isPage'=>$data['nextPage']));
    }


    public function uploadShareImgId(){
        $uid    = session('uid');
        $eid    = I('post.eid',0,'intval');
        $mediaID= I('post.media',null);
        $ret=WeixinModel::getWxServerImg($mediaID);
        if ($ret==''){
            $this->ajaxReturn(array('status'=>1,'msg'=>'上传失败，请重试或联系管理员'));
        }else{
            EventsModel::getJoinInstance()->where("eid={$eid} and uid={$uid}")->setField('sharePic',$ret);
            $this->ajaxReturn(array('status'=>0,'msg'=>'分享图片上传成功','pic'=>$ret));
        }
    }

    //活动详情
    public function info(){
        $uid=session('uid')+0;
        $id = I("get.id",0,'intval');
        if(!$id) redirect(U('Events/index'));//数据为空返回列表
        $info =EventsModel::getEventsInfo($id,$uid);// response('Events/getEventsInfo', array('id'=>$id));
        EventsModel::addHot($id);
        
        if($info['status'] != 0) redirect(U('Events/index'));//数据为空返回列表
        S('EVENTSINFO_'.$id,$info,10);

        if($info['data']['jumpMode']==EventsModel::JUMP_MODE_LIST){
            redirect($info['data']['jumpURL']);
            die;
        }

        if($this->isWechat) {
            $domain=UtilsModel::getFullDomain();
            //微信分享相关
            $this->smarty->assign('isWxShare', true);
            $this->smarty->assign('wxTitle', $info['data']['title']);
            $this->smarty->assign('wxDesc',  $info['data']['shareUri']);
            $this->smarty->assign('wxLink', $domain.U('info?id=' . $id . '&fromUid=' . $uid));
            $this->smarty->assign('wxImage', C('UPLOAD_RESOURCE_PREFIX').$info['data']['imgList']);
            $this->smarty->assign('wxObjType',OBJ_TYPE_ACTIVITY);
            $this->smarty->assign('wxObjID',$id);

            $this->smarty->assign('chooseImg', true);
        }

        //作业分享
        $data = EventsModel::getTaskShare($id);
        $this->smarty->assign('tasks',$data);

        $askFollow=0;

        $hasFollow=UserModel::checkFollow($uid);
        if(!$hasFollow && M('e_events',null,DB_MAIN_CFG)->where('id='.$id)->getField('mustFollow')==1){
            $askFollow=1;
        }

        $photo=EventsModel::getEventsPhoto($id,0,5);
        $this->smarty->assign('photo',$photo);

        $this->smarty->assign('qrcode_path',C('WEIXIN_QRCODE_PATH'));//二维码
        $this->smarty->assign('askFollow',$askFollow);

        $this->smarty->assign('loginuri',U("User/login")."&uri=".urlencode(U("Events/info")."&id=$id"));
        $this->smarty->assign('title',C('SITE_NAME'));//$info['data']['title']

        $content=$info['data']['content'];
        $matches=array();
        if(preg_match_all('/<img[^>]+\s*(src\s*=[^>]*)>/', $info['data']['content'], $matches1)) {
            $matches=$matches1[1];
        }

        foreach ($matches as $raw){
            $new=str_replace('src','class="lazy" data-original',$raw);
            $content=str_replace($raw,$new,$content);
        }
        $info['data']['content']= $content;


        $this->smarty->assign('info',$info['data']);
        $this->smarty->assign('JOIN_STATUS_APPLY',EventsModel::JOIN_STATUS_APPLY);
        $this->smarty->assign('LOGIN_URL',WECHAT_AUTHORIZATION_URI);
        $this->smarty->display("Event_v2/info.html");
    }

    //检查用户作业上交情况
    public function checkUserTask(){
        $uid = session('uid');
        $id = I('get.id',0,'intval');
        $uri = urlencode(U('Events/info')."&id=".$id);
        if(!$uid) redirect(U('User/login')."&uri=".$uri);//数据为空返回列表

        $data = EventsModel::getUserTaskInfo($uid);

        if($data['status'] == 1){
            $this->ajaxReturn($data);
        }
        if(count($data['data']) > 0){
            //有未上交的作业
            $this->ajaxReturn(array('status'=>2,'data'=>$data['data']));
        } else{
            $this->ajaxReturn(array('status'=>0));
        }
    }

    //活动报名界面
    public function apply(){
        $uid = session('uid');

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $id = I('get.id',0,'intval');
        $uri = urlencode(U('Events/info')."&id=".$id);
        if(!$uid) redirect(U('User/login')."&uri=".$uri);//数据为空返回列表

        $info = S('EVENTSINFO_'.$id);
        if(!$info) $info =EventsModel::getEventDetail($id);
        if(!$info) redirect('Events/index');//数据为空返回列表
        $cfgImgPosition = C('imgPosition');
        $size = $cfgImgPosition['IMG_EVENT_APPLY'];
        $info['data']['imgList'] = C('FILE_SHOW_PATH').$size['width'].'x'.$size['height'].substr($info['data']['imgList'],strlen(dirname(dirname($info['data']['imgList']))));

        if($info['status'] == 1) redirect(U('Events/index'));//数据为空返回列表

        $this->smarty->assign('DELIVERY_SEND',PointMallModel::DELIVERY_SEND);
        $this->smarty->assign('DELIVERY_CARD',PointMallModel::DELIVERY_CARD);


        $hasFollow=UserModel::checkFollow($uid);
        if(!$hasFollow && M('e_events',null,DB_MAIN_CFG)->where('id='.$id)->getField('mustFollow')==1){
            $askFollow=1;
        }
        $this->smarty->assign('askFollow',$askFollow);




        if ($info['data']['needNickname']==1){
            $babyBirthday=UserModel::getInstance()->where("uid={$uid}")->getField('babyNickname');
            $this->smarty->assign('babyNickname',substr($babyBirthday,0,7));
        }
        if ($info['data']['needSex']==1){
            $babyBirthday=UserModel::getInstance()->where("uid={$uid}")->getField('babySex');
            $this->smarty->assign('babySex',substr($babyBirthday,0,7));
        }
        if ($info['data']['needAge']==1){
            $babyBirthday=UserModel::getInstance()->where("uid={$uid}")->getField('babyBirthday');
            $this->smarty->assign('babyBirthday',substr($babyBirthday,0,7));
        }


        if ($info['data']['needDeliver']!=0){
            $deliverInfo=UserModel::getInstance()->where("uid={$uid}")->field('deliverArea,deliverAddress')->find();
            $this->smarty->assign('street',$deliverInfo['deliverArea']);
            $this->smarty->assign('address',$deliverInfo['deliverAddress']);
        }


        if(strlen($info['data']['addressPool'])>3){
            $addressArray=explode("\r\n",$info['data']['addressPool']);
            $addressEnabledArray=array();
            foreach ($addressArray as $one){
                $one=trim($one);
                if(strlen($one)>0){
                    $addressEnabledArray[]=$one;
                }
            }
            if (count($addressEnabledArray)>0){
                $this->smarty->assign('addressPool',$addressEnabledArray);
            }
        }
        if(strlen($info['data']['otherPool'])>3){
            $addressArray=explode("\r\n",$info['data']['otherPool']);
            $addressEnabledArray=array();
            foreach ($addressArray as $one){
                $one=trim($one);
                if(strlen($one)>0){
                    $addressEnabledArray[]=$one;
                }
            }
            if (count($addressEnabledArray)>0){
                $this->smarty->assign('otherPool',$addressEnabledArray);
                $this->smarty->assign('otherTitle',$info['data']['otherTitle']);
            }
        }

        if (strlen($info['data']['jsonData'])>3){
            $ext=json_decode($info['data']['jsonData'],1);
            $this->smarty->assign('ext',$ext);
        }




        $vipInfo=UserModel::getUserVipInfo($uid);
        $isVIP=0;
        if ($vipInfo['vipEndTime']>time() && $vipInfo['vipEventJoinTimes']>0){//会员
            $isVIP=1;
        }
        $this->smarty->assign('isVIP',$isVIP);
        $this->smarty->assign('title',C('SITE_NAME').'-活动报名');//$info['data']['title']
        $this->smarty->assign('info',$info['data']);

        $this->smarty->assign('qrcode_path',C('WEIXIN_QRCODE_PATH'));//二维码
        $this->smarty->assign('LOGIN_URL',WECHAT_AUTHORIZATION_URI);
        $this->smarty->display("Event_v2/apply.html");
    }

    //活动 确定报名
    public function join(){

        $uid = session('uid');
        $nickname = session('nickname');
        $id = I('get.id',0,'intval');
        $data = array('status'=>1, 'msg'=>'参数错误');
        if(!$uid || !$id) $this->ajaxReturn($data);//数据为空返回列表

        $useVIP= I('get.useVIP',0,'int');
        $phone = I('get.phone',null,'strip_tags');
        $realName = I('get.realname',null,'strip_tags');
        $mark = I('get.mark',null,'strip_tags');
        $street = I('get.street',null,'strip_tags');
        $address = I('get.address',null,'strip_tags');
        $addressPool = I('get.addressPool',null,'strip_tags');
        $otherPool = I('get.otherPool',null,'strip_tags');
        $ext = I('get.ext',null,'strip_tags');

        $babyNickname=I('get.babyNickname','','strip_tags');
        $babySex=I('get.babySex','','strip_tags');
        $babyBirthday=I('get.babyBirthday','','strip_tags');
        if(!filedPreMatch('phone', $phone)){
            $data['msg'] = '手机号码格式错误';
            $this->ajaxReturn($data);
        }

        if(UtilsModel::strlen($realName)<C('NICKNAME_LENGTH_MIN') || UtilsModel::strlen($realName)>C('NICKNAME_LENGTH_MAX')){
            $data['msg'] = '真实姓名格式错误';
            $this->ajaxReturn($data);
        }

        if($mark && true !== $maskStr = checkCleanWord($mark) ){
            $data['msg'] = '留言中不能包含'.$maskStr;
            $this->ajaxReturn($data);
        }


        //查看是不是绑定手机号码 绑定的手机号为空则需要填写验证码 完成绑定
        if(session('bindPhone') == ''){
            $code = I('get.code',null,'strip_tags');
            $res = UserModel::bindUserPassword($uid, $phone, $code, $realName);
            if($res['status']){
                $this->ajaxReturn($res);
            }else{
                self::resetUserSessions($res['data']);//重新绑定后UID用可能发生变化
                $uid = session('uid');
                $nickname = session('nickname');
            }
        }

        $hasFollow=UserModel::checkFollow($uid);
        if(!$hasFollow && M('e_events',null,DB_MAIN_CFG)->where('id='.$id)->getField('mustFollow')==1){
                $data = array('status'=>2, 'msg'=>'本次活动要求您必须关注本公众号才可参与');//要求关注
                $this->ajaxReturn($data);
        }

        $data =EventsModel::apply($id,$uid,$nickname,$phone,$realName,$mark,$babyNickname,$babySex,$babyBirthday,$useVIP,$street,$address,$addressPool,$otherPool,$ext);
        $data['hasFollow']=$hasFollow;
        $this->ajaxReturn($data);
    }


    public function photos(){
        $eid=I("get.eid",0,'int');
        $uid=I("get.uid",0,'int');
        $eventInfo=EventsModel::getEventInstance()->where("id={$eid}")->field("title,showListTime")->find();
        $photos=EventsModel::getEventsPhoto($eid,$uid,100);
        $this->smarty->assign('info',$eventInfo);
        $this->smarty->assign('list',$photos);
        $this->smarty->display("Event_v2/photo.html");
    }


    public function allPhoto(){
        $uid=I('get.uid',0,'int');
        if ($uid>0){
            $where="uid={$uid}";
        }else{
            $where="1";
        }
        $photos=EventsModel::getPhotoInstance()->where($where)->group("eid")->order("eid desc")->getField("eid,GROUP_CONCAT(path) as album,count(1) as num",true);
        $eids="0";
        foreach ($photos as $eid=>$item){
            $eids.=",".$eid;
        }
        $events=EventsModel::getEventInstance()->where("id in({$eids})")->getField("id,title,showListTime",true);


        $this->smarty->assign('uid',$uid);
        $this->smarty->assign('events',$events);
        $this->smarty->assign('photos',$photos);
        $this->smarty->display("Event_v2/photos.html");
    }



    //活动报名人员记录
    public function applyLog(){
        $id = I('get.id',0,'intval');
        $type = I('get.type',1,'intval');
        $data = array('status'=>1, 'msg'=>'参数错误');
        if(!$id) $this->ajaxReturn($data);//数据为空返回列表

        $uid = session("uid")+0;
        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $eventTitle=EventsModel::getEventInstance()->where("id={$id}")->getField("title");

        $this->smarty->assign('title',$eventTitle);
        $this->smarty->assign('objType',$type);
        $this->smarty->assign('objID',$id);
        $this->smarty->display("Event_v2/applyLog.html");
    }

    //活动报名人员记录 加载更多
    public function loadMoreLog(){
        $page = I('get.page',1,'intval');
        $id = I('get.id',0,'intval');
        $type = I('get.type',1,'intval');
        $uid = session('uid')+0;
        $data = EventsModel::getEventsApplyListLog($uid,$id,$type,$page,12);

        $this->smarty->assign('uid',$uid);
        $this->smarty->assign('eid',$id);

        $this->smarty->assign('list',$data['data']);
        $this->smarty->assign('hasTask',$data['hasTask']);
        $this->smarty->assign('unjoin',EventsModel::JOIN_STATUS_UNJOIN);
        $this->smarty->assign('noTask',EventsModel::EVENTS_TASK_DONOT);
        $html = $this->smarty->fetch('Event_v2/applyLogList.html');
        $this->ajaxReturn(array('status'=>0, 'dataHTML'=>$html, 'isPage'=>$data['nextPage']));
    }

    //提交作业页面
    public function pushTask(){
        UtilsModel::checkLogin();
        $uid=session('uid')+0;
        $eid = I('get.eid',0,'intval');
        $this->smarty->assign('eid',$eid);
        $info = EventsModel::getTask($eid,$uid);
        if($info){
            $info['imgList'] = explode(',',$info['imgList']);
        }
        $this->smarty->assign('obj',$info);

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->assign('title',"提交作业");
        $this->smarty->display("Events/task.html");
    }
    //提交作业
    public function submitTask(){
        UtilsModel::checkLogin();
        $uid = session('uid')+0;
        $eid = I('get.eid',0,'intval');
        $content = I('get.content',null,'strip_tags');
        $imgList = I('get.imgList',null);
        $imgStr = null;

        $contentLen = count($content);
        if($contentLen<1 || $contentLen >40){
            $this->ajaxReturn(array('status'=>1,'msg'=>'作业内容应控制在1-40个字内，请审核后重新提交！'));
        }

        $imgLen = count($imgList);
        if($imgLen>0 && $imgLen<5){
            $imgStr = implode(',',$imgList);
        }else{
            $this->ajaxReturn(array('status'=>1,'msg'=>'上传图片应1-4张为宜，请审核后重新提交！'));
        }

        $res = EventsModel::saveTask($uid,$eid,$content,$imgStr);
        $this->ajaxReturn($res);
    }

    //取消报名
    public function cancelRegistration(){
        $uid = session('uid');
        $id = I('get.id',0,'intval');
        $data = array('status'=>1, 'msg'=>'参数错误');
        if(!$uid || !$id) $this->ajaxReturn($data);//数据为空返回列表
        $res = EventsModel::cancelRegistration($id,$uid);
        $this->ajaxReturn($res);
    }

}